package com.vframework.system.role.controller;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.util.StringUtil;
import com.vframework.base.controller.BaseController;
import com.vframework.base.exception.BaseException;
import com.vframework.base.model.BaseBean;
import com.vframework.common.constant.SessionConstant;
import com.vframework.common.service.DictService;
import com.vframework.system.menu.model.MenuBean;
import com.vframework.system.org.model.OrgBean;
import com.vframework.system.org.service.OrgService;
import com.vframework.system.role.model.RoleBean;
import com.vframework.system.role.service.RoleService;
import com.vframework.system.user.service.UserService;

/***************************************************************
 * Name:        RoleController.java
 * Create At:   2018年5月7日
 * Module:      
 * Description: [角色管理]
 * @author      ztshan
 * ------------------------------------------------------------
 * 修改历史
 * 序号         日期                       修改人               修改原因
 * 1    2018年5月7日      ztshan    
 * 2
***************************************************************/
@Controller
@RequestMapping("RoleController")
public class RoleController extends BaseController {

    private static final String BASE_PATH = "com/vframework/system/role/pages/";
    
    @Autowired
    private RoleService roleService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;

    /**
     * Author:zhangyanling Create At:2012-05-29 Description:
     * [系统管理-初始页面，查询角色信息列表]
     * 
     * @return String
     */
    @RequestMapping(value = "begin")
    public String begin(Model model) throws Exception {
        return getRoleList(model);
    }
    
    /**
     * Author:shanzhitong
     * Create At:2010-04-22 Description: [系统管理-查询角色列表]
     * 
     * @return String
     */
    @RequestMapping(value = "getRoleList")
    private String getRoleList(Model model) {
        try {
            String orgType = (String) super.session.getAttribute(SessionConstant.SESSION_ORG_TYPE);
            if (!"0".equals(orgType)) {
                super.paramMap.put("param_siId", (String) session.getAttribute(SessionConstant.SESSION_ORG_ID));
            }
            List<RoleBean> resultList = roleService.getRoleList(super.paramMap);
            model.addAttribute("resultList", resultList);
            model.addAttribute("method", "getRoleList");
        } catch (Exception e) {
            super.message("查询失败: " + e.getMessage());
            return getRoleList(model);
        }
        return BASE_PATH + "roleList";
    }

    /**
     * Author:shanzhitong 
     * Create At:2010-06-30 Description: 跳转到添加页面
     * 
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "add")
    public String add(Model model) throws Exception {
        String orgType = (String) request.getSession().getAttribute(SessionConstant.SESSION_ORG_TYPE);
        if (!"0".equals(orgType)) {
            super.paramMap.put("param_orgId", (String) session.getAttribute(SessionConstant.SESSION_ORG_ID));
        }
        List<OrgBean> orgList = orgService.getOrgList(super.paramMap);
        model.addAttribute("roleBean", new RoleBean());
        model.addAttribute("method", "add");
        model.addAttribute("orgList", orgList);
        model.addAttribute("roleTypeList", getRoleListByJurisdiction());
        return BASE_PATH + "roleMenuList";
    }
    
    @SuppressWarnings("unchecked")
    private List<BaseBean> getRoleListByJurisdiction() {
        //判断是否有超级管理员权限
        List<RoleBean> roleSet = (List<RoleBean>)super.session.getAttribute(SessionConstant.SESSION_USER_ROLE);
        boolean hasSuper = false;
        for (RoleBean role : roleSet) {
            if ("0".equals(role.getRoleType())) {
                hasSuper = true;
                break;
            }
        }
        List<BaseBean> roleList = DictService.getTypeList("role_type");
        //只有超级管理员可以添加超级管理员角色
        if (!hasSuper) {
            Iterator<BaseBean> it = roleList.iterator();
            while (it.hasNext()) {
                BaseBean role = it.next();
                if ("0".equals(role.getCode())) {
                    it.remove();
                    break;
                }
            }
        }
        return roleList;
    }
    
    /**
     * Create At:   2017年9月27日
     * @author   ztshan
     * @param    
     * @return    
     * @description  ajax返回按照orgId查询的menuList
     */
    @RequestMapping(value = "getRoleMenuList")
    @ResponseBody
    public List<MenuBean> getRoleMenuList() {
        String orgId = request.getParameter("orgId");
        String method = request.getParameter("method");
        String roleId = request.getParameter("roleId");
        if (StringUtil.isEmpty(orgId)) {
            return null;
        }
        String userId = (String) session.getAttribute(SessionConstant.SESSION_USER_ID);
        super.paramMap.put("param_userId", userId);
        super.paramMap.put("param_orgId", orgId);
        super.paramMap.put("param_roleId", roleId);
        List<MenuBean> roleMenuList = null;
        try {
            if ("addSave".equals(method))
                roleMenuList = roleService.getRoleMenuForAddList(orgId);
            else if ("editSave".equals(method))
                roleMenuList = roleService.getMenuByRole(super.paramMap);
        } catch (BaseException e) {
            super.message("查询失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
        return roleMenuList;
    }
    
    /**
     * Author:shanzhitong 
     * Create At:2010-04-22 Description: [用户管理-查询用户列表]
     * 
     * @return String
     */
    @RequestMapping(value = "getMenuByRole")
    public String getMenuByRole(Model model) {
        try {
            String roleId = (String)super.paramMap.get("param_roleId");
            if (roleId == null || "".equals(roleId)) {
                super.message("参数错误");
                return getRoleList(model);
            }
            RoleBean roleBean = roleService.getRoleById(roleId);
            super.paramMap.put("param_orgId", roleBean.getOrgId());
            List<MenuBean> list = roleService.getMenuByRole(super.paramMap);
            List<OrgBean> orgList = orgService.getOrgList(super.paramMap);
            model.addAttribute("roleMenuList", list);
            model.addAttribute("method", "edit");
            model.addAttribute("roleBean", roleBean);
            model.addAttribute("orgList", orgList);
            model.addAttribute("roleTypeList", getRoleListByJurisdiction());
        } catch (Exception e) {
            super.message("查询失败: " + e.getMessage());
            return getRoleList(model);
        }
        return BASE_PATH + "roleMenuList";
    }
    
    /**
     * Author:shanzhitong 
     * Create At:2010-04-22 Description: [角色管理-删除角色信息]
     * 
     * @return String
     */
    @RequestMapping(value = "deleteRele")
    public String deleteRele(Model model) {
        try {
            String[] ids = request.getParameterValues("ids");
            //验证roleIds下是否有用户存在
            super.paramMap.put("param_roleIds", ids);
            int userCount = userService.getCount(super.paramMap);
            super.paramMap.remove("param_roleIds");
            if (userCount > 0) {
                super.message("删除失败：角色下存在用户，请先删除用户再删除角色!");
                return getRoleList(model);
            }
            super.paramMap.put("ids", ids);
            String siId = (String) session.getAttribute(SessionConstant.SESSION_ORG_ID);
            String userId = (String) session.getAttribute(SessionConstant.SESSION_USER_ID);
            super.paramMap.put("param_userId", userId);
            super.paramMap.put("param_siId", siId);
            roleService.deleteRole(super.paramMap);
            super.message("删除角色成功");
            roleService.insertLog(super.MakeLogBean(super.LOG_DELETE_KEY, "删除角色", super.paramMap.toString()));
            model.addAttribute("method", "deleteRele");
        } catch (Exception e) {
            super.message("删除角色失败: " + e.getMessage());
        }
        return getRoleList(model);

    }

    /**
     * Author:shanzhitong 
     * Create At:2010-04-22 Description: [用户管理-修改用户，保存用户信息]
     * 
     * @return String
     */
    @RequestMapping(value = "editSave")
    public String editSave(RoleBean roleBean, Model model) {
        try {
            String userId = (String) session.getAttribute(SessionConstant.SESSION_USER_ID);
            super.paramMap.put("param_userId", userId);
            super.paramMap.put("param_siId", roleBean.getOrgId());
            roleBean.setUserId(userId);
            roleService.editRole(roleBean);
            super.message("修改角色成功");
            roleService.insertLog(super.MakeLogBean(super.LOG_UPDATE_KEY, "修改角色", roleBean.toString()));
            model.addAttribute("method", "editSave");
        } catch (Exception e) {
            super.message("修改角色失败: " + e.getMessage());
        }
        return getRoleList(model);

    }

    /**
     * Author:shanzhitong 
     * Create At:2010-04-22 Description: [用户管理-添加用户，保存用户信息]
     * 
     * @return String
     */
    @RequestMapping(value = "addSave")
    public String addSave(RoleBean roleBean, Model model) {
        try {
            String siId = (String) session.getAttribute(SessionConstant.SESSION_ORG_ID);
            String userId = (String) session.getAttribute(SessionConstant.SESSION_USER_ID);
            super.paramMap.put("param_userId", userId);
            super.paramMap.put("param_siId", siId);
            roleService.addRole(roleBean);
            super.message("添加角色成功");
            roleService.insertLog(super.MakeLogBean(super.LOG_ADD_KEY, "添加角色", roleBean.toString()));
            model.addAttribute("method", "addSave");
            model.addAttribute("roleBean", roleBean);
        } catch (Exception e) {
            super.message("添加角色失败: " + e.getMessage());
            return getRoleList(model);
        }
        return getRoleList(model);
    }
}